﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;

namespace TcpClient
{
    internal class Program
    {
        // 客户端创建网络流 字节数组
        private static byte[] buffer = new byte[1024];

        static void Main(string[] args)
        {
            // 将字符串ip转化为ip地址
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            // 创建客户端套接字连接对象，套接字类型为网络流，协议为tcp
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                // 客户端通过ip地址连接服务端
                clientSocket.Connect(new IPEndPoint(ip, 8012));
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                Console.WriteLine("连接服务器失败!");
                return;
            }
            // 客户端接收服务端消息
            int receiveLength = clientSocket.Receive(buffer);
            Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(buffer, 0, receiveLength));
            // 连续间隔1秒发送5次消息
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    //每次间隔1秒
                    Thread.Sleep(1000);
                    string sendMessage = "client send Message Hello";
                    // 客户端发送消息给服务端
                    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                    Console.WriteLine("向服务器发送消息:{0}", sendMessage);
                }
                catch
                {
                    //关闭连接
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
            Console.WriteLine("发送完毕,按回车键退出");
            Console.WriteLine();
        }

    }
}
